package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 叶熠彬
 * @description: 订单查询实现类
 * @date: 2022/7/29 23:02
 */
@Slf4j
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderShippingMapper shippingMapper;

    @Autowired
    OrderItemMapper itemMapper;

    @Autowired
    OrderConverter converter;

    /**
     * 查询当前用户的历史订单列表
     *
     * @author: 叶熠彬
     * @date: 2022/7/30 09:54
     * @param: [request]
     * @return: com.cskaoyan.order.dto.OrderListResponse
     */
    @Override
    public OrderListResponse orderList(OrderListRequest request) {
        OrderListResponse response = new OrderListResponse();
        try {
            request.requestCheck();
            Long userId = request.getUserId();
            PageHelper.startPage(request.getPage(), request.getSize());

            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            criteria.andNotEqualTo("status", OrderConstants.ORDER_STATUS_TRANSACTION_DELETED);
            // 排序
            if (StringUtils.isEmpty(request.getSort())) {
                example.orderBy("updateTime").desc();
            } else {
                example.orderBy(request.getSort()).desc();
            }

            List<Order> orders = orderMapper.selectByExample(example);
            List<OrderDetailInfo> detailInfos = new ArrayList<>();
            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = converter.order2detailInfo(order);
                String orderId = order.getOrderId();
                // 查询物流
                OrderShipping orderShipping = shippingMapper.selectByPrimaryKey(orderId);
                OrderShippingDto orderShippingDto = converter.shipping2dto(orderShipping);

                // 查询商品
                OrderItem orderItemForQuery = new OrderItem();
                orderItemForQuery.setOrderId(orderId);
                List<OrderItem> orderItems = itemMapper.select(orderItemForQuery);
                List<OrderItemDto> orderItemDtos = converter.item2dto(orderItems);

                // 封装到DetailInfo
                orderDetailInfo.setOrderShippingDto(orderShippingDto);
                orderDetailInfo.setOrderItemDto(orderItemDtos);

                detailInfos.add(orderDetailInfo);
            }
            PageInfo<Order> orderPageInfo = new PageInfo<>(orders);

            // 返回response
            response.setData(detailInfos);
            response.setTotal(orderPageInfo.getTotal());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 查询订单明细
     *
     * @author: 叶熠彬
     * @date: 2022/7/30 12:25
     * @param: [request]
     * @return: com.cskaoyan.order.form.OrderDetail
     */
    @Override
    public OrderDetail orderDetail(OrderDetailRequest request) {
        OrderDetail response = new OrderDetail();
        try {
            // 参数校验
            request.requestCheck();
            String orderId = request.getOrderId();

            // 查询订单信息
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order == null) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), "该订单不存在");
            }

            response.setUserId(order.getUserId());
            response.setUserName(order.getBuyerNick());
            response.setOrderTotal(order.getPayment());
            response.setOrderStatus(order.getStatus());


            // 查询商品信息
            List<OrderItem> orderItems = itemMapper.queryByOrderId(orderId);
            List<OrderItemDto> orderItemDtos = converter.item2dto(orderItems);
            response.setGoodsList(orderItemDtos);

            // 查询物流
            OrderShipping orderShipping = shippingMapper.selectByPrimaryKey(order);
            OrderShippingDto orderShippingDto = converter.shipping2dto(orderShipping);
            if (orderShippingDto != null) {
                response.setTel(orderShippingDto.getReceiverMobile());
                response.setStreetName(orderShippingDto.getReceiverAddress());
                response.setUserName(orderShippingDto.getReceiverName());
            }

            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
